package com.search.service.Impl;

import com.alibaba.fastjson.JSON;
import com.hly.common.to.es.SkuEsModel;
import com.search.config.RequestElasticSearchConfig;
import com.search.constant.EsConstant;
import com.search.service.ProductSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

/**
 * @program: SpringCloud
 * Author HLY
 * @desc
 * @create: 2021-04-23 17:49
 **/
@Slf4j
@Service
public class ProductSaveServiceImpl implements ProductSaveService {

    @Autowired
    RestHighLevelClient client;

    /**
     * 商品上架，信息保存到ElasticSearch
     * @param skuEsModels
     * @return
     */
    @Override
    public boolean  productStatusUp(List<SkuEsModel> skuEsModels) throws IOException {
        //将数据批量保存到es中
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel model : skuEsModels) {
            //构造保存 索引 请求
            IndexRequest indexRequest = new IndexRequest(EsConstant.PRODUCT_INDEX);
            //设置索引id
            indexRequest.id(model.getSkuId().toString());
            //设置具体保存的内容
            String s = JSON.toJSONString(model);
            indexRequest.source(s, XContentType.JSON);
            //添加保存请求
            bulkRequest.add(indexRequest);
        }
        BulkResponse bulk = client.bulk(bulkRequest, RequestElasticSearchConfig.COMMON_OPTIONS);
        boolean b = bulk.hasFailures();
        if(b) {
            log.info("商品上架完成");
        }
        return b;
    }
}
